let mongo = require('../db/mongo');

const wordDao = {
    async getAnyWord(uid) {
        const database = mongo.client.db('kaoyanbang_db');
        const wordsCollection = database.collection('word');
        const progressCollection = database.collection('wordProgress');

        // 第一步：获取 uid 对应的用户，所有 level 为 “认识” 的单词 id
        let knownWordIds = await progressCollection.aggregate([
                { $match: { uid } },                         // 筛选 uid 对应的用户
                { $unwind: "$progress" },                    // 展开 progress 数组
                { $match: { "progress.level": "认识" } },    // 筛选 level 为 “认识” 的单词
                { $project: { "progress.id": 1, _id: 0 } }   // 只保留单词 id
            ]).toArray();
        knownWordIds = knownWordIds.map(item => item.progress.id);

        // 第二步：从 words 集合中排除这些 “认识” 的单词，返回剩下的单词信息，限制为 20 个
        let result = await wordsCollection.find(
                { id: { $nin: knownWordIds } }               // 排除已知的单词 id
            ).project({ id: 1, word: 1, meaningList: 1, exampleSentenceList: 1, _id: 0 })  // 选择需要的字段
            .limit(20)
            .toArray();  // 将游标转换为数组

        return result;
    },
    // 保存用户单词进度
    async saveUserProgress(uid, progress, time) {
        let data = {
            uid, progress, time
        };
        return mongo.client.db('kaoyanbang_db').collection('wordProgress').insertOne(data);
    },
    // 读取用户单词进度
    async getUserProgress(uid) {
        return mongo.client.db('kaoyanbang_db').collection('wordProgress').find({ uid }).toArray();
    },
    // 获取这个单词
    async loadThisWord(wordId) {
        return mongo.client.db('kaoyanbang_db').collection('word').findOne({ id: wordId });
    }
};

module.exports = wordDao;
